package com.epoint.utils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSourceFactory;

public class JDBCUtils {
	// 1.定义成员变量 DataSource
	private static DataSource ds;

	static {
		try {
			// 1.加载配置文件
			Properties pro = new Properties();
			pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
			// 2.获取DataSource
			ds = DruidDataSourceFactory.createDataSource(pro);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取连接
	 * 
	 * @return
	 * @throws SQLException
	 */
	public static Connection getConnection() throws SQLException {
		return ds.getConnection();
	}
	/**
	 * 释放资源
	 * @param pstmt
	 */
	public static void close(PreparedStatement pstmt) {
		close(null, pstmt, null);
	}
	/**
	 * 释放资源
	 * 
	 * @param stmt
	 * @param conn
	 */
	public static void close(PreparedStatement pstmt, Connection conn) {
		close(null, pstmt, conn);
	}

	/**
	 * 释放资源
	 * @param rs
	 * @param pstmt
	 * @param conn
	 */
	public static void close(ResultSet rs, PreparedStatement pstmt, Connection conn) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (pstmt != null) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (conn != null) {
			try {
				conn.close();// 归还连接
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 获取连接池方法
	 * 
	 * @return
	 */
	public static DataSource getDataSource() {
		return ds;
	}

	public static void main(String[] args) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			conn = JDBCUtils.getConnection();
			String sql = "select * from t_employee";
			pstmt = conn.prepareStatement(sql);

			rs = pstmt.executeQuery();

			while (rs.next()) {
				System.out.println(rs.getString("name"));
			}

		} catch (SQLException throwables) {
			throwables.printStackTrace();
		} finally {
			JDBCUtils.close(rs, pstmt, conn);
		}
	}
}
